package DAO;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HibernateUtil {
	
	 private static Logger logger = LoggerFactory.getLogger("Server");
	 private static SessionFactory sessionFactory = null;
	 private static ServiceRegistry serviceRegistry = null;
	 private static Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); 
	    static {
	        try {
	        	serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
	        			.buildServiceRegistry(); 
	        	sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	        } catch (Exception e) {
	        	logger.error("Error in creating service factory");
	        }
	    }
	    
	    public static Session beginTransaction() {
	    	Session hibernateSession = HibernateUtil.getSession();
	    	hibernateSession.beginTransaction();
	    	return hibernateSession;
	    }
	    	 
	    public static void commitTransaction() {
	    	HibernateUtil.getSession().getTransaction().commit();
	    }
	    	 
	    public static void rollbackTransaction() {
	    	HibernateUtil.getSession().getTransaction().rollback();
	    }
	    	 
	    public static void closeSession() {
	    	HibernateUtil.getSession().close();
	    }
	    	 
	    public static Session getSession() {
	    	Session hibernateSession = sessionFactory.getCurrentSession();
	    	return hibernateSession;
	    }
}

